import { _decorator, Component, EventTouch, input, Input, Node, quat, Quat, Tween, tween, v2, v3, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 触摸旋转3D物体
 */
@ccclass('TouchRotation3D')
export class TouchRotation3D extends Component {

    addEvent() {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    offEvent() {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.off(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    protected update(dt: number): void {
        if (this._isAutoRotate_b) {
            this.autoRotate(dt)
        }
    }

    private onTouchStart() {
        this.closeRotate()
    }

    private _touchMoveDelta: Vec2;
    private onTouchMove(event: EventTouch) {
        // 自传
        // 这个物体模型‘锚点’在正中心效果比较好
        // 垂直的轴，右手  
        //  
        //  旋转轴
        //  ↑
        //  ---> 触摸方向
        this._touchMoveDelta = event.getDelta();
        this.rotate(this._touchMoveDelta.clone())
    }

    private onTouchCancel() {
        this.openRotate(true)
    }

    private onTouchEnd(event: EventTouch) {
        // console.log("onTouchEnd", event, event.getDelta());
        this.openRotate(true)
    }

    private _quat = quat();

    /**
     * 旋转
     * @param delta : {x: x轴 ;y: y轴} 
     */
    private rotate(delta: Vec2) {
        //旋转轴，根据相似三角形求出
        const axis = v3(-delta.y, delta.x, 0); 
        //旋转角度
        const rad = delta.length() * 1e-2;
        //当前的四元数
        const quat_cur = this.node.getRotation()
        this._quat = quat();
        //当面的四元数绕旋转轴旋转
        Quat.rotateAround(this._quat, quat_cur, axis.normalize(), rad)
        // 旋转后的结果 / 当前的四元数 / 旋转轴 / 旋转四元数
        this.node.setRotation(this._quat);
    }


    private _isAutoRotate_b: boolean = false;
    private openRotate(isDelay: boolean = false) {
        if (isDelay) {
            this.unschedule(this.delayOpenRotate)
            this.scheduleOnce(this.delayOpenRotate, 5)
        } else {
            this.delayOpenRotate()
        }
    }

    private closeRotate() {
        this._isAutoRotate_b = false
        this.unschedule(this.delayOpenRotate)
    }
    private delayOpenRotate() {
        this._isAutoRotate_b = true
    }
    
    private autoRotate(dt: number) {
        const delta = v2(-20 * dt, 0)
        this.rotate(delta)
    }
}


// 四元素插值
// const outQuat = quat()
// Quat.slerp(outQuat, this._rotationLerp_obj.start, this._rotationLerp_obj.end, this._rotationLerp_obj.lerpVelue)
// this.node.setRotation(outQuat)